# coding=utf8
import time

from libs.wx import WxInfo
from libs.dbs import model_redis
from libs.help import str_to_time, time_to_str


# 存在数组中,key=appid,value=wechat
class WxAccounts:
    def __init__(self):
        self.pool = {}

    def get(self, appid):
        if appid not in self.pool:
            self.set(appid)
        return self.pool[appid]

    def set(self, appid):
        self.pool[appid] = WxInfo(appid)

    def delete(self, appid):
        if appid in self.pool:
            del self.pool[appid]

    @staticmethod
    def get_left(appid):
        redis_key = "wechat:{appid}".format(appid=appid)
        num = model_redis.get(redis_key)
        if num is None:
            WxAccounts.update_left(appid, 8, True)
            return 8
        else:
            return int(num)

    @staticmethod
    def update_left(appid, n, new=False):
        redis_key = "wechat:{appid}".format(appid=appid)
        if new:
            model_redis.set(redis_key, n)
            # 默认0点更新
            today = str_to_time(time_to_str("%Y%m%d"), format="%Y%m%d")
            ddl = today + 60 * 60 * 24
            model_redis.expire(redis_key, ddl - int(time.time()))
        else:
            model_redis.incrby(redis_key, -n)
        return model_redis.get(redis_key)


model_user_wx = WxAccounts()
